from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage

from django.conf import settings


def page(queryset, request):
    page_number = request.GET.get('page', settings.ARTICLES_PER_NO)
    per_page = request.GET.get('per_page', settings.ARTICLES_PER_PAGE)
    try:
        per_page = int(per_page)
    except ValueError:
        per_page = settings.ARTICLES_PER_PAGE

    paginator = Paginator(queryset, per_page)

    try:
        current_page = paginator.page(page_number)
    except PageNotAnInteger:
        current_page = paginator.page(settings.ARTICLES_PER_NO)
    except EmptyPage:
        current_page = paginator.page(paginator.num_pages)

    data_list = []
    for item in current_page:
        item_dict = {}
        for field in item._meta.get_fields():
            field_name = field.name
            item_dict[field_name] = getattr(item, field_name)
        data_list.append(item_dict)

    data = {
        'total_pages': paginator.num_pages,
        'current_page': current_page.number,
        'articles': data_list
    }
    return data
